import axios from 'axios';
import { ElMessage } from 'element-plus';

// 创建 Axios 实例
const myAxios = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080',
  timeout: 10000,
  // withCredentials: true,
});

// 请求拦截器
myAxios.interceptors.request.use(
  (config) => {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    } 
    return config;
  },
  (error) => {
    console.error('请求异常:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
myAxios.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 1 && res.code!== 0) {
      ElMessage.error(res.message || '请求失败');
      return Promise.reject(new Error(res.message || '请求失败'));
    }
    return res; // 返回数据部分
  },
  (error) => {
    console.error('响应异常:', error.message,import.meta.env.VITE_API_BASE_URL);
    ElMessage.error('请求失败，请稍后重试');
    return Promise.reject(error);
  }
);

export default myAxios;
